require 'MVVM.Sources.View.Adaptor'

DynamicToggleGroupAdaptor = class('DynamicToggleGroupAdaptor', Adaptor)

function DynamicToggleGroupAdaptor:ctor(gameObjectContain , propertyNameDataList, propertyNameIndex, _viewCallBack, binder)
    local gameObjectList = {}
    local toggleGroup = gameObjectContain:GetComponent('ToggleGroup')
    local viewModelIndex = nil
    binder:RegisterEvent(function(viewModel, property)
        viewModelIndex = property
    end, function()
        for i = 1, #gameObjectList do
            local toggle = gameObjectList[i]:GetComponent('Toggle')
            toggle.onValueChanged:RemoveAllListeners()
        end
    end, propertyNameIndex)

    binder:Add(propertyNameIndex,function(oldValue,newValue)
        if newValue == nil or oldValue == newValue then
            return
        end

        print("oldValueoldValueoldValue ",oldValue,newValue)
        if gameObjectList[newValue] then
            gameObjectList[newValue]:GetComponent('Toggle').isOn = true

            if _viewCallBack ~= nil then
                _viewCallBack(oldValue,newValue)
            end
        else
            if gameObjectList[oldValue] then
                gameObjectList[oldValue]:GetComponent('Toggle').isOn = false
            end
        end
    end)
    binder:Add(propertyNameDataList,function(oldValue,newValue)
        if newValue == nil or oldValue == newValue then
            return
        end
        gameObjectList = {}
        for index = 0,gameObjectContain.childCount-1 do
            local trans = gameObjectContain:GetChild(index)
            local toggle = trans:GetComponent('Toggle')
            toggle.group = toggleGroup
            toggle.onValueChanged:RemoveAllListeners()      --先移除复用绑定的事件

            toggle.onValueChanged:AddListener(function(isOn)
                print("bbbbbbbbbbbbbbb ",isOn,index)
                if isOn then
                    if viewModelIndex then
                        viewModelIndex.Value = index + 1
                    end
                end
            end)
            table.insert( gameObjectList,trans)
        end

    end)
end